package com.shxc.smarttrade.old.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.old.activity.AddTradeCategoryActivity;
import com.shxc.smarttrade.quotation.old.AllQuotationActivity;
import com.shxc.smarttrade.main.MainActivity;
import com.shxc.smarttrade.old.adapter.TransactionAdapter;
import com.shxc.smarttrade.MyApplication;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.TradeCategory;
import com.shxc.smarttrade.old.bean.TransactionDatas;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.constants.URLContents;
import com.shxc.smarttrade.old.myinterface.TransactionItemClickListener;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.myview.RecycleViewTwoDivider;
import com.shxc.smarttrade.old.utils.MyOkHttpUtils;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * Created by jcdev1 on 2017/5/9.
 */

public class TransactionFragment extends Fragment implements View.OnClickListener {

    private View rootView;
    LinearLayoutManager manager;
    TransactionAdapter adapter;
    private Runnable runnable;
    private boolean tvLeftStatus = false;
    private MyProgressDialog dialog;
    private int userId;

    @BindView(R.id.rv_trading_product)
    RecyclerView rvTradingProduct;
    @BindView(R.id.tv_left)
    TextView tvLeft;
    @BindView(R.id.rl_right)
    RelativeLayout rlRight;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;

    private String symbol = "";
    private List<TransactionDatas.DataBean.SymbolsBean> oldData = new ArrayList<>();
    private List<TransactionDatas.DataBean.SymbolsBean> newData = new ArrayList<>();
    private List<TransactionDatas.DataBean.SymbolsBean> sbb;
    private Map<String, String> map = new HashMap<>();

    public List<TransactionDatas.DataBean.SymbolsBean> money;
    public List<TransactionDatas.DataBean.SymbolsBean> index;
    public List<TransactionDatas.DataBean.SymbolsBean> metal;
    public List<TransactionDatas.DataBean.SymbolsBean> energy;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    TransactionDatas tDatas = (TransactionDatas) msg.obj;
                    if (tDatas == null) return;
                    String errCode = tDatas.getErr_code();
                    String errorMsg = tDatas.getErr_msg();
                    if (errCode.equals("0")) {
                        sbb = tDatas.getData().getSymbols();
                        symbol = "";
                        for (int i = 0; i < sbb.size(); i++) {
                            map.put(sbb.get(i).getSymbolEn(), sbb.get(i).getSymbolCn());
                            if (i == 0) {
                                symbol += sbb.get(i).getSymbolEn();
                            } else {
                                symbol += "," + sbb.get(i).getSymbolEn();
                            }
                        }
                        List<TransactionDatas.DataBean.SymbolsBean> testSB = new ArrayList<TransactionDatas.DataBean.SymbolsBean>();
                        adapter.setOldDatas(testSB);
                        adapter.setNewDatas(sbb);
                        ((MainActivity) getActivity()).startTimerListener(symbol, 1);
                    } else {
                        Toast.makeText(getContext(), errorMsg, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 1:
                    int position = msg.arg1;
                    adapter.deleteDatas(position);
                    initDatas(userId);
                    break;
                case 2:
                    TradeCategory tc = (TradeCategory) msg.obj;
                    String errorcode = tc.getErr_code();
                    String errmessage = tc.getErr_msg();
                    if (errorcode.equals("0")) {
                        List<TradeCategory.DataBean.SymbolsBean> sb = tc.getData().getSymbols();
//                        List<TradeCategory.DataBean.SymbolsBean> money = new ArrayList<>();
//                        List<TradeCategory.DataBean.SymbolsBean> index = new ArrayList<>();
//                        List<TradeCategory.DataBean.SymbolsBean> metal = new ArrayList<>();
//                        List<TradeCategory.DataBean.SymbolsBean> energy = new ArrayList<>();
                        //将数据分组
                        for (TradeCategory.DataBean.SymbolsBean symbo : sb) {
                            if (symbo.getGroup().equals("0")) {
//                                money.add(symbo);

                            } else if (symbo.getGroup().equals("1")) {
//                                index.add(symbo);
                            } else if (symbo.getGroup().equals("2")) {
//                                metal.add(symbo);
                            } else {
//                                energy.add(symbo);
                            }
                        }
                    } else {
                    }
                    break;
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_transaction, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);
        initView();
        initListener();
        userId = SpUtils.getInt(getContext(), "userId", 0);
        dialog.show();
        initDatas(userId);
//        getAllSymbol(userId);

        return rootView;
    }

    /**
     * 初始化view
     */
    private void initView() {
        tabLayout.addTab(tabLayout.newTab().setText("自选"));
        tabLayout.addTab(tabLayout.newTab().setText("外汇"));
        tabLayout.addTab(tabLayout.newTab().setText("原油"));
        tabLayout.addTab(tabLayout.newTab().setText("贵金属"));
        tabLayout.addTab(tabLayout.newTab().setText("指数"));


        manager = new LinearLayoutManager(getContext());
        rvTradingProduct.setLayoutManager(manager);
        rvTradingProduct.addItemDecoration(new RecycleViewTwoDivider(getContext(), LinearLayout.VERTICAL, 1, getResources().getColor(R.color.dividing_line_color)));
        rvTradingProduct.setAdapter(adapter = new TransactionAdapter(getContext(), manager));
        dialog = new MyProgressDialog(getContext());
        dialog.setCancelable(false);

    }

    /**
     * 初始化监听器
     */
    private void initListener() {
        adapter.setOnItemClickListener(new TransactionItemClickListener() {
            @Override
            public void itemClick(TransactionDatas.DataBean.SymbolsBean sb, int position) {
//                Intent intent = new Intent(getActivity(), StockChartUpgradeActivity.class);
                Intent intent = new Intent(getActivity(), AllQuotationActivity.class);
                intent.putExtra("symbol", sb.getSymbolEn());
                intent.putExtra("symbolCn", sb.getSymbolCn());
                intent.putExtra("tag", 0);
                intent.putExtra("digits", sb.getDigits());
                startActivity(intent);

                MobclickAgent.onEvent(getContext(), "transaction_detail");//友盟统计该点击事件发生次数

            }

            @Override
            public void clickToDelete(TransactionDatas.DataBean.SymbolsBean sb, int position) {

                deleteCategory(userId, sb.getSymbolEn(), position);

            }
        });
        tvLeft.setOnClickListener(this);
        rlRight.setOnClickListener(this);
    }

    /**
     * 从服务器获取户主所关注的项目数据
     */
    private void initDatas(final int userId) {
        //每次在重新获取数据之前都要暂停实时数据发射器
        ((MainActivity) getActivity()).stopTimerListener();
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getContext(), "accessToken", ""));
        map.put("userId", userId + "");
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.TRANSACTION_FRAGMENT_FOCUS, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {
                dialog.dismiss();

            }

            @Override
            public void success(String response, int id) {
                if (response == null) return;
                Gson gson = new Gson();
                TransactionDatas td = gson.fromJson(response, TransactionDatas.class);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = td;
                handler.sendMessage(msg);
                dialog.dismiss();
            }
        });
    }

    /**
     * 初始化数据
     */
    private void getAllSymbol(int userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getActivity(), "accessToken", ""));
        map.put("userId", userId + "");
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.ADD_TRADE_CATEGORY_ACTIVITY_SYMBOL, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void success(String response, int id) {

                Gson gson = new Gson();
                TradeCategory tradeCategory = gson.fromJson(response, TradeCategory.class);
                Message msg = Message.obtain();
                msg.what = 2;
                msg.obj = tradeCategory;
                handler.sendMessage(msg);
            }

            @Override
            public void faild(Call call, Exception e, int id) {
            }
        });
    }

    /**
     * 删除数据
     *
     * @param userId
     * @param symbolEn
     */
    private void deleteCategory(int userId, String symbolEn, final int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("accessToken", SpUtils.getString(getContext(), "accessToken", ""));
        map.put("userId", userId + "");
        map.put("symbolEn", symbolEn);
        MyOkHttpUtils.getServiceDatas(getActivity(),map, URLContents.TRANSACTION_FRAGMENT_DELETE, new MyOkHttpUtils.ServiceStatus() {
            @Override
            public void faild(Call call, Exception e, int id) {

            }

            @Override
            public void success(String response, int id) {
                if (response == null) return;
                JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
                String errCode = jsonObject.get("err_code").getAsString();
                String errMsg = jsonObject.get("err_msg").getAsString();
                if (errCode.equals("0")) {
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.arg1 = position;
                    handler.sendMessage(msg);

                } else {
                    MyApplication.showToast(getContext(), errCode);
                }
            }
        });
    }

    /**
     * 必须加注解，否则无效
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventDatas event) {
        if (event.getTagOne().equals(EventContents.MAIN_ACTIVITY_REAL_TIME_QUOTE_TWO)) {
            //1、接收实时变化的数据；2、控制某个条目闪烁和更改数据
            List<RealTimeQuoteDatas.DataBean.QuoteBean> ab = (List<RealTimeQuoteDatas.DataBean.QuoteBean>) event.getResponse();
//            Log.e("Transaction", ab.size() + "");
            realTimeUpdateAdapter(ab);

        } else if (event.getTagOne().equals(EventContents.ADD_TRADE_CATEGORY_ACTIVITY_TWO)) {
            tabLayout.getTabAt(0).select();
            initDatas(userId);
        } else if (event.getTagOne().equals(EventContents.MAIN_ACTIVITY_REAL_TIME_QUOTE_FOUR)) {
            startListener();
        }
    }

    /**
     * 实时更新Adapter
     *
     * @param ab
     */
    private void realTimeUpdateAdapter(List<RealTimeQuoteDatas.DataBean.QuoteBean> ab) {
        if (newData.size() == 0) {
            oldData = sbb;
        } else {
            oldData.clear();
            oldData.addAll(newData);
        }

        /////////////////////////////////
        Map<String, RealTimeQuoteDatas.DataBean.QuoteBean> mapab = new HashMap<>();
        for (RealTimeQuoteDatas.DataBean.QuoteBean quoteBean : ab) {
            mapab.put(quoteBean.getSymbol(), quoteBean);
        }
        if (mapab.size() != 0) {
            newData.clear();
            for (int i = 0; i < sbb.size(); i++) {
                TransactionDatas.DataBean.SymbolsBean sBean = new TransactionDatas.DataBean.SymbolsBean();
                TransactionDatas.DataBean.SymbolsBean syb = sbb.get(i);
                if (mapab.containsKey(syb.getSymbolEn())) {
                    RealTimeQuoteDatas.DataBean.QuoteBean quoteB = mapab.get(syb.getSymbolEn());
                    sBean.setSymbolCn(syb.getSymbolCn());
                    sBean.setSymbolEn(syb.getSymbolEn());
                    sBean.setAsk(quoteB.getAsk());
                    sBean.setBid(quoteB.getBid());
                    sBean.setMarket(quoteB.getMarket());
                    sBean.setSpread(0);
                    sBean.setDigits(syb.getDigits());
                    newData.add(sBean);
                } else {
                    newData.add(syb);
                }

            }
        }
        ////////////////////////////////

        adapter.setOldDatas(oldData);
        adapter.setNewDatas(newData);
    }

    /**
     * 启动实时消息发射器
     */
    public void startListener() {

        if (symbol.length() > 0) {
            ((MainActivity) getActivity()).startTimerListener(symbol, 1);
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        handler.removeCallbacks(runnable);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_left:
                if (tvLeftStatus) {
                    adapter.isShowDelet(false);
                    tvLeft.setText("编辑");
                    tvLeftStatus = false;
                    MobclickAgent.onEvent(getContext(), "transaction_edit");//友盟统计该点击事件发生次数
                } else {
                    adapter.isShowDelet(true);
                    tvLeft.setText("完成");
                    tvLeftStatus = true;
                }
                break;
            case R.id.rl_right:
                startActivity(new Intent(getActivity(), AddTradeCategoryActivity.class));
                MobclickAgent.onEvent(getContext(), "transaction_add");//友盟统计该点击事件发生次数
                break;
        }
    }
}
